package com.jinbo.footmessageworker.sign;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.jinbo.footmessageworker.BaseActivity;
import com.jinbo.footmessageworker.MyApplication;
import com.jinbo.footmessageworker.R;
import com.jinbo.footmessageworker.httpbean.LookSignBean;
import com.jinbo.footmessageworker.httpbean.SignBean;
import com.jinbo.footmessageworker.httpbean.TurnsBean;
import com.jinbo.footmessageworker.httpretrofit.BusinessController;
import com.jinbo.footmessageworker.httpretrofit.Listener;
import com.jinbo.footmessageworker.login.LoginActivity;
import com.jinbo.footmessageworker.utils.DialogUtils;
import com.jinbo.footmessageworker.utils.LocalPreferencesHelper;
import com.jinbo.footmessageworker.utils.TimeUtils;
import com.jinbo.footmessageworker.view.TitleBarView;

public class SignActivity extends BaseActivity implements View.OnClickListener{
     Button mGoOnDutyBtn,mGoOffDutyBtn,mGoOutServeBtn,mComeBackServeBtn;
     LocationManager mLocationManger;
    String provider;
    TextView mDateTv,mTurnTv;
    String user_id;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign);
        TitleBarView titleBarView = (TitleBarView) findViewById(R.id.titleBar);
        titleBarView.setCenterTitle("签到");
        titleBarView.setLeftBackButtonIsVisibler(true);
        titleBarView.setListener(TitleBarView.TitleBarEnum.ll_leftBackImageLayout, this);
        user_id= MyApplication.local.getString(LocalPreferencesHelper.USER_ID);
        mLocationManger=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        //String serviceName = Context.LOCATION_SERVICE;
        provider =  mLocationManger.getBestProvider(criteria, true);
        initView();
        initdata();

    }
    void initView()
    {
        mDateTv=(TextView)findViewById(R.id.date);
        mTurnTv=(TextView)findViewById(R.id.turn);
        mComeBackServeBtn=(Button)findViewById(R.id.come_back_serve);
        mGoOutServeBtn=(Button)findViewById(R.id.go_out_serve);
        mGoOnDutyBtn=(Button)findViewById(R.id.go_on_duty);
        mGoOffDutyBtn=(Button)findViewById(R.id.go_off_duty);
        mComeBackServeBtn.setOnClickListener(this);
        mGoOutServeBtn.setOnClickListener(this);
        mGoOnDutyBtn.setOnClickListener(this);
        mGoOffDutyBtn.setOnClickListener(this);
        
    }
  //  String s="(null)";
    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.left_back_layout:
                finish();
                break;
            case R.id.go_on_duty:
                 if(mGoOnDutyBtn.isEnabled()) {

                     if(mLocationManger.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                         mLocationManger.requestLocationUpdates(provider, 1000, (float) 100.0,new LocationListener(){
                             @Override
                             public void onLocationChanged(Location location) {
                                 if (location != null) {
                                     dismissProgressDialog();
                                 /*    Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
                                     Log.w("Location", "Current altitude = "
                                             + location.getAltitude());
                                     Log.w("Location", "Current latitude = "
                                             + location.getLatitude());
                                     s = "("+location.getLongitude()+","+ location.getLatitude()+")";
                                     mGoOnDutyBtn.setEnabled(false);
                                     mGoOnDutyBtn.setText("上班已签到" + s);
                                     mLocationManger.removeUpdates(this);*/
                                     updateData(location.getLongitude(),location.getLatitude(),1,this);
                                 }
                             }

                             @Override
                             public void onStatusChanged(String provider, int status, Bundle extras) {

                             }

                             @Override
                             public void onProviderEnabled(String provider) {

                             }

                             @Override
                             public void onProviderDisabled(String provider) {

                             }
                         });

                         showProgressDialog("正在定位...");
                     }
                     else
                     {
                         new DialogUtils(this, "center",false,0)
                                 .setMessage("请打开GPS开关")
                                 .setButtons(null, "确定",
                                         new DialogUtils.OnDialogButtonClickListener() {
                                             @Override
                                             public void onDialogButtonClick(Context context, DialogUtils builder, Dialog dialog, int dialogId, int which) {

                                             }
                                         }).create().show();
                     }


                 }
                break;
            case R.id.go_off_duty:
                if(mGoOffDutyBtn.isEnabled())
                {
                    if(mLocationManger.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                        mLocationManger.requestLocationUpdates(provider, 1000, (float) 100.0,new LocationListener(){
                            @Override
                            public void onLocationChanged(Location location) {
                                if (location != null) {
                                    dismissProgressDialog();
                                   /* Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
                                    Log.w("Location", "Current altitude = "
                                            + location.getAltitude());
                                    Log.w("Location", "Current latitude = "
                                            + location.getLatitude());
                                    s = "("+location.getLongitude()+","+ location.getLatitude()+")";
                                    mGoOffDutyBtn.setEnabled(false);
                                    mGoOffDutyBtn.setText("下班已签退"+s);
                                    mLocationManger.removeUpdates(this);*/
                                    updateData(location.getLongitude(),location.getLatitude(),2,this);

                                }
                            }

                            @Override
                            public void onStatusChanged(String provider, int status, Bundle extras) {

                            }

                            @Override
                            public void onProviderEnabled(String provider) {

                            }

                            @Override
                            public void onProviderDisabled(String provider) {

                            }
                        });

                        showProgressDialog("正在定位...");
                    }
                    else
                    {
                        new DialogUtils(this, "center",false,0)
                                .setMessage("请打开GPS开关")
                                .setButtons(null, "确定",
                                        new DialogUtils.OnDialogButtonClickListener() {
                                            @Override
                                            public void onDialogButtonClick(Context context, DialogUtils builder, Dialog dialog, int dialogId, int which) {

                                            }
                                        }).create().show();
                    }


                }
                break;
            case R.id.go_out_serve:
                if(mGoOutServeBtn.isEnabled()) {

                    if(mLocationManger.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                        mLocationManger.requestLocationUpdates(provider, 1000, (float) 100.0,new LocationListener(){
                            @Override
                            public void onLocationChanged(Location location) {
                                if (location != null) {
                                    dismissProgressDialog();/*
                                    Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
                                    Log.w("Location", "Current altitude = "
                                            + location.getAltitude());
                                    Log.w("Location", "Current latitude = "
                                            + location.getLatitude());
                                    s = "("+location.getLongitude()+","+ location.getLatitude()+")";
                                    mGoOutServeBtn.setEnabled(false);
                                    mGoOutServeBtn.setText("外服已签出"+s);
                                    mComeBackServeBtn.setEnabled(true);
                                    mComeBackServeBtn.setText("外服签回");
                                    mLocationManger.removeUpdates(this);*/


                                    updateData(location.getLongitude(), location.getLatitude(), 3, this);
                                }
                            }

                            @Override
                            public void onStatusChanged(String provider, int status, Bundle extras) {

                            }

                            @Override
                            public void onProviderEnabled(String provider) {

                            }

                            @Override
                            public void onProviderDisabled(String provider) {

                            }
                        });

                        showProgressDialog("正在定位...");
                    }
                    else
                    {
                        new DialogUtils(this, "center",false,0)
                                .setMessage("请打开GPS开关")
                                .setButtons(null, "确定",
                                        new DialogUtils.OnDialogButtonClickListener() {
                                            @Override
                                            public void onDialogButtonClick(Context context, DialogUtils builder, Dialog dialog, int dialogId, int which) {

                                            }
                                        }).create().show();
                    }



                }
              
                break;
            case R.id.come_back_serve:
                if(mComeBackServeBtn.isEnabled())
                {
                    if(mLocationManger.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                        mLocationManger.requestLocationUpdates(provider, 1000, (float) 100.0,new LocationListener(){
                            @Override
                            public void onLocationChanged(Location location) {
                                if (location != null) {
                                    dismissProgressDialog();
                            /*        Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
                                    Log.w("Location", "Current altitude = "
                                            + location.getAltitude());
                                    Log.w("Location", "Current latitude = "
                                            + location.getLatitude());
                                    s = "("+location.getLongitude()+","+ location.getLatitude()+")";
                                    mComeBackServeBtn.setEnabled(false);
                                    mComeBackServeBtn.setText("外服已签回"+s);
                                    mGoOutServeBtn.setEnabled(true);
                                    mGoOutServeBtn.setText("外服签出");

                                    mLocationManger.removeUpdates(this);*/


                                    updateData(location.getLongitude(), location.getLatitude(), 4, this);
                                }
                            }

                            @Override
                            public void onStatusChanged(String provider, int status, Bundle extras) {

                            }

                            @Override
                            public void onProviderEnabled(String provider) {

                            }

                            @Override
                            public void onProviderDisabled(String provider) {

                            }
                        });

                        showProgressDialog("正在定位...");
                    }
                    else
                    {
                        new DialogUtils(this, "center",false,0)
                                .setMessage("请打开GPS开关")
                                .setButtons(null, "确定",
                                        new DialogUtils.OnDialogButtonClickListener() {
                                            @Override
                                            public void onDialogButtonClick(Context context, DialogUtils builder, Dialog dialog, int dialogId, int which) {

                                            }
                                        }).create().show();
                    }



                }
                
                
                break;
        }
    }



    void updateData(double lon,double lat,final int kind, final LocationListener listener)
    {

      //  int  start_date= TimeUtils.getDay(TimeUtils.getNowMillis() - 24 * 60 * 60 * 1000);
        BusinessController.getInstance().sign(user_id,lon,lat,TimeUtils.getNowTimeFormat(),TimeUtils.getNowDateFormat(),kind,new Listener<SignBean>() {
            @Override
            public void onStart(Object... params) {
                showProgressDialog("正在上传数据...");
                //mLoadView.setVisibility(View.VISIBLE);
                //mPullRefreshLayout.setRefreshing(true);
                //mLoadView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onComplete(SignBean result, Object... params) {
                dismissProgressDialog();
                //adapter.setorders(result.orders);
                // mPullRefreshLayout.setRefreshing(false);
                //mLoadView.setVisibility(View.GONE);
                // mCallBacks2.change(result.orders);
                // OrderActivity.this.
                // orders = result.orders;
                // mCallBacks2.change(result.orders);
                 show("已经上传完数据，签到成功");
                 String s="("+TimeUtils.getNowTimeFormat()+")";
                 if(kind==1)
                 {
                     mGoOnDutyBtn.setEnabled(false);
                     mGoOnDutyBtn.setText("上班已签到" + s);
                     mLocationManger.removeUpdates(listener);
                 }
                if(kind==2)
                {
                    mGoOffDutyBtn.setEnabled(false);
                    mGoOffDutyBtn.setText("下班已签退"+s);
                    mLocationManger.removeUpdates(listener);

                }
                if(kind==3)
                {
                    mGoOutServeBtn.setEnabled(false);
                    mGoOutServeBtn.setText("外服已签出" + s);
                    mComeBackServeBtn.setEnabled(true);
                    mComeBackServeBtn.setText("外服签回");
                    mLocationManger.removeUpdates(listener);
                   MyApplication.local.saveOrUpdate(user_id+LocalPreferencesHelper.G0_OUT_SERVER, "1");
                    MyApplication.local.saveOrUpdate(user_id+LocalPreferencesHelper.G0_OUT_TIME,s);

                }
                if(kind==4)
                {
                    mComeBackServeBtn.setEnabled(false);
                    mComeBackServeBtn.setText("外服已签回" + s);
                    mGoOutServeBtn.setEnabled(true);
                    mGoOutServeBtn.setText("外服签出");
                    mLocationManger.removeUpdates(listener);
                    MyApplication.local.saveOrUpdate(user_id+LocalPreferencesHelper.G0_OUT_SERVER, "2");
                    MyApplication.local.saveOrUpdate(user_id+LocalPreferencesHelper.G0_OUT_TIME,s);


                }



            }

            @Override
            public void onFail(final String msg, Object... params) {
                // mLoadView.setVisibility(View.VISIBLE);
                dismissProgressDialog();
                //mLoadView.setVisibility(View.GONE);
                // mPullRefreshLayout.setRefreshing(false);
                if (TextUtils.isEmpty(msg)) {
                } else {
                    show(msg);
                }
            }
        });
    }
    void initdata()
    {
        String sate=MyApplication.local.getString(user_id+LocalPreferencesHelper.G0_OUT_SERVER);
        String s=MyApplication.local.getString(user_id+LocalPreferencesHelper.G0_OUT_TIME);
        if(sate.equals("1"))
        {
            mGoOutServeBtn.setEnabled(false);
            mGoOutServeBtn.setText("外服已签出" + s);
        }
        else if(sate.equals("2"))
        {
            mComeBackServeBtn.setEnabled(false);
            mComeBackServeBtn.setText("外服已签回" + s);
        }
        BusinessController.getInstance().lookSign(user_id, TimeUtils.getNowDateFormat(),  new Listener<LookSignBean>() {
            @Override
            public void onStart(Object... params) {
                showProgressDialog("初始化数据...");
                //mLoadView.setVisibility(View.VISIBLE);
                //mPullRefreshLayout.setRefreshing(true);
                //mLoadView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onComplete(LookSignBean result, Object... params) {
                dismissProgressDialog();
                //adapter.setorders(result.orders);
                // mPullRefreshLayout.setRefreshing(false);
                //mLoadView.setVisibility(View.GONE);
                // mCallBacks2.change(result.orders);
                // OrderActivity.this.
                // orders = result.orders;
                // mCallBacks2.change(result.orders);
                mDateTv.setText(result.turn.date);
                if(result.turn.turn.equals("A"))
                   mTurnTv.setText(result.turn.turn+"(早班)");
                if(result.turn.turn.equals("B"))
                    mTurnTv.setText(result.turn.turn+"(中班)");
                if(result.turn.turn.equals("C"))
                    mTurnTv.setText(result.turn.turn+"(晚班)");
                if(result.turn.turn.equals(""))
                {
                    mGoOnDutyBtn.setEnabled(false);
                    mGoOffDutyBtn.setEnabled(false);
                }
                if(result.on_sign.time!=null)
                {
                    mGoOnDutyBtn.setEnabled(false);
                    mGoOnDutyBtn.setText("上班已签到(" + result.on_sign.time+")");
                }
                if(result.off_sign.time!=null)
                {
                    mGoOffDutyBtn.setEnabled(false);
                    mGoOffDutyBtn.setText("下班已签退("+result.off_sign.time+")");
                }

            }

            @Override
            public void onFail(final String msg, Object... params) {
                // mLoadView.setVisibility(View.VISIBLE);
                dismissProgressDialog();
                //mLoadView.setVisibility(View.GONE);
                // mPullRefreshLayout.setRefreshing(false);
                if (TextUtils.isEmpty(msg)) {
                } else {
                    show(msg);
                }
            }
        });
    }
/*
    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            dismissProgressDialog();
            Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
            Log.w("Location", "Current altitude = "
                    + location.getAltitude());
            Log.w("Location", "Current latitude = "
                    + location.getLatitude());
            s = "("+location.getLongitude()+","+ location.getLatitude()+")";
            mGoOnDutyBtn.setEnabled(false);
            mGoOnDutyBtn.setText("上班已签到" + s);
            mLocationManger.removeUpdates(this);
        }
        //locationManager.setTestProviderEnabled(provider, false);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }*/
}
